# -*- coding: utf-8 -*-
'''
Created on Sep 8, 2012

@author: bbg
'''

from logic.login_session_mgr import LoginSessionMgr
import datetime
from logic.cdkey_mgr import CdkeyManager
from core.util.debug import Log
from core.db.shopx.config_cook_method_class import ConfigCookMethodClass
from core.db.shopx.config_cook_method  import ConfigCookMethod
from core.db.shopx.config_cook_relation import ConfigCookRelation
from core.db.shopx.config_dish_class import ConfigDishClass
from core.db.shopx.config_dish import ConfigDish
from core.db.shopx.config_floor import ConfigFloor
from core.db.shopx.config_order_mode import ConfigOrderMode
from core.db.shopx.config_payment import ConfigPayment
from core.db.shopx.config_printers import ConfigPrinters
from core.db.shopx.config_reason import ConfigReason
from core.db.shopx.config_room import ConfigRoom
from core.db.shopx.config_stat_class import ConfigStatClass
from core.db.shopx.config_unit_relation import ConfigUnitRelation
import json
from sqlalchemy.orm import class_mapper
from webob import Request, Response
from service.server_config import SrvConfig
import uuid

def application(environ, start_response):
    '''
        entrance of apache wsgi application
    '''    
    req = Request(environ)
    res = Response()
    
    ShopConfigService.process(req, res)
    
    return res(environ, start_response)



class ShopConfigService(object):
    '''
        分店配置类信息操作:
        1. download configure
        2. update configure
        3. insert configure
        4. delete configure
    '''
    __setup__ = False
    log = None   
    
    
    @staticmethod
    def process(req, res):
        if ShopConfigService.__setup__ == False:
            Log.setPath(SrvConfig.getLogPath())
            ShopConfigService.log = Log()            
            ShopConfigService.__setup__ = True    
            
            
        try:
            #检查 TOKEN 的有效性 
            dbsession = SrvConfig.getDefaultDBSession()
            typestr = req.params["type"]
            
            company_id = req.params["company_id"]
            username = req.params["username"]
            token = req.params["token"]
            
            if LoginSessionMgr.isSessionValid(company_id, username, token, dbsession) is False:
                res.json = {'ret':107, 'msg':'token is invalid'}
                ShopConfigService.log.e("CompanyService:process, token is invalid")
                return

            shopConfigService = ShopConfigService(dbsession)                                     
            if typestr == "all":
                shopConfigService.getConfigAll(req, res)
            else:  
                if req.params['method'] == 'get':
                    return shopConfigService.getShopConfig(req, res)
                elif req.params['method'] == 'set':
                    return shopConfigService.setShopConfig(req, res)
                 
                res.json = {'ret':-1, 'msg':'unknown method'}
                ShopConfigService.log.e("ShopConfigService:process, unknown method %s" % req.params['method'])
        except Exception, e:
                res.json = {'ret':-1, 'msg':'exception'}
                ShopConfigService.log.e("ShopConfigService:process, exception %s" % e)
        finally:
            dbsession.close()

    def __init__(self, dbsession):
        self.dbsession = dbsession


    def setShopConfig(self, req, res):
        '''
            set shop configuration
        '''        
        config_table = req.params['config_table']
                
        config_table_classes = {}
        config_table_classes["config_cook_method_class"] = ConfigCookMethodClass
        config_table_classes["config_cook_method"] = ConfigCookMethod
        config_table_classes["config_cook_relation"] = ConfigCookRelation
        config_table_classes["config_dish_class"] = ConfigDishClass
        config_table_classes["config_dish"] = ConfigDish
        config_table_classes["config_floor"] = ConfigFloor
        config_table_classes["config_order_mode"] = ConfigOrderMode
        config_table_classes["config_payment"] = ConfigPayment
        config_table_classes["config_printers"] = ConfigPrinters
        config_table_classes["config_reason"] = ConfigReason
        config_table_classes["config_room"] = ConfigRoom
        config_table_classes["config_stat_class"] = ConfigStatClass
        config_table_classes["config_unit_relation"] = ConfigUnitRelation
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            return self._setConfigAction(req, res, table_class)
        else:
            return self.response(-1, "unkonw configure")
        
    def _setConfigAction(self, req, res, table_class):
        '''
            对写配置的响应
            table_class 要操作的表对应的ORM类
        '''
        try:
            cmd = req.params['cmd']
            #过滤出要更新的表字段名和字段值
            exclude_fields = ['company_id','op_shop_id', 'username', 
                              'token', 'cmd', 'config_table', 'where_name', 
                              'where_value', 'sign']
            
            table_fields = {}
            for param in req.params.keys():
                if param not in exclude_fields:
                    table_fields[param] = req.params[param]
                    
            company_id = req.params['company_id']
            shop_id = req.params['op_shop_id']
            table_class.doMapping(company_id, shop_id)                            
            if cmd == 'add':
                # 增加记录操作                
                table_object = table_class()
                for field in table_fields:
                    table_object.__setattr__(field, table_fields[field])
                    
                try:
                    self.dbsession.add(table_object)
                    self.dbsession.commit()
                except Exception, e:
                    ShopConfigService.log.e("ShopConfigService:setConfigAction() add table %s exception %s" % (table_object, e))
                    res.json = {'ret':-1, 'msg':'exception'}
                    return
                               
                res.json = {"ret":0,"msg":"add ok"}                
            elif cmd == 'update':                
                #更新记录操作
                #获取要修改的表where字段
                where_name = req.params['where_name']
                where_value = req.params['where_value']
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                query_result = self.dbsession.query(table_class).filter(columnAttr == where_value)
                
                if query_result.count() ==0:
                    ShopConfigService.log.e("ShopConfigService:setConfigAction(): no such record")
                    res.json = {'ret':-1, 'msg':'no such record'}
                    return
                                
                for table_object in query_result:
                    for field in table_fields:
                        table_object.__setattr__(field, table_fields[field])
                        
                self.dbsession.commit()
  
                res.json = {'ret':0, 'msg' : 'update ok'}                
            elif cmd == 'del':                
                #删除记录操作
                
                where_name = req.params['where_name']
                where_value = req.params['where_value']
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                self.dbsession.query(table_class).filter(columnAttr == where_value).delete()
                self.dbsession.commit()
                    
                res.json = {'ret':0, 'msg' : 'delete ok'}                
        except Exception, e:
            ShopConfigService.log.e('ShopConfigService.setConfigAction(): exception:%s' % e)
            res.json = {'ret':-1, 'msg' : 'exception'}
            
        
    def getShopConfig(self, req, res):
        '''
            get shop configuration
        '''
        config_table_classes = {}
        config_table_classes["config_cook_method_class"] = ConfigCookMethodClass
        config_table_classes["config_cook_method"] = ConfigCookMethod
        config_table_classes["config_cook_relation"] = ConfigCookRelation
        config_table_classes["config_dish_class"] = ConfigDishClass
        config_table_classes["config_dish"] = ConfigDish
        config_table_classes["config_floor"] = ConfigFloor
        config_table_classes["config_order_mode"] = ConfigOrderMode
        config_table_classes["config_payment"] = ConfigPayment
        config_table_classes["config_printers"] = ConfigPrinters
        config_table_classes["config_reason"] = ConfigReason
        config_table_classes["config_room"] = ConfigRoom
        config_table_classes["config_stat_class"] = ConfigStatClass
        config_table_classes["config_unit_relation"] = ConfigUnitRelation
        
        
        #排序字段列表
        config_orderby = {}
        config_orderby["config_cook_method_class"] ="rank_id"
        config_orderby["config_cook_method"] = "rank_id"
        config_orderby["config_cook_relation"] = "id"
        config_orderby["config_dish_class"] = "rank_id"
        config_orderby["config_dish"] = "rank_id"
        config_orderby["config_floor"] = "rank_id"
        config_orderby["config_order_mode"] = "order_mode_class asc,rank_id asc"
        config_orderby["config_payment"] = "id"
        config_orderby["config_printers"] = "id"
        config_orderby["config_reason"] = "problem_class asc ,rank_id asc"
        config_orderby["config_room"] = "rank_id"
        config_orderby["config_stat_class"] = "rank_id"
        config_orderby["config_unit_relation"] = "inner_rank_id"

        config_table = req.params['type']
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            orderby = config_orderby[config_table]
            return self._getConfigAction(req, res, table_class, orderby)
        else:
            return self.response(-1, "unkonw configure")
        

    def _getConfigAction(self, req, res, table_class, orderby):
        '''
            对读配置的响应
            table_class 要操作的表对应的ORM类
        '''
        try:

            #过滤出要更新的表字段名和字段值
            company_id = req.params['company_id']
            shop_id = req.params['op_shop_id']
            table_class.doMapping(company_id, shop_id)            
            table_fields = {}                       
            for col in (class_mapper(table_class).mapped_table.c):
                table_fields[col.name]=col.name
                                                    
            #获取记录操作                      
            if req.params.has_key('zfilter_where') == False:
                query_result = self.dbsession.query(table_class).filter().order_by(orderby).all()
            else:
                query_result = self.dbsession.query(table_class).filter(req.params['zfilter_where']).order_by(orderby).all()
                                        
            returnlist = []
                
            dicmy = {}
            dicmy["ret"] = 0
            dicmy["msg"] = "success"
            icount = 0
            
            for r in query_result:
                icount = 1
                dicmydata = {}       
                for field in  table_fields:
                    temp = getattr(r, table_fields[field])                  
                    if type(temp) is datetime.datetime:
                        dicmydata[field] = str(temp)                        
                    else:
                        dicmydata[field] = temp
                         
                strtemp=json.dumps(dicmydata)
                returnlist.append(strtemp)   

            if icount == 0:    
                ShopConfigService.log.e("ShopConfigService:getConfigAction(): no such record")
                res.json = {'ret':-1, 'msg':'no such record'}
                return              
            else:        
                dicmy['data'] = returnlist
                res.json = dicmy                     
        except Exception, e: 
            ShopConfigService.log.e('ShopConfigService:getConfigAction(): exception:%s' % e)
            res.josn = {'ret':-1, 'msg': 'exceptioin'}
        
                
    def getConfigAll(self, req, res):
        '''
            匹配公司ID和SHOPID
        '''
        try:                 
            cdkey = req.params['cdkey']
            uuid = req.params['uuid']
            
            dbmapb = CdkeyManager.hasbindUuidCDkey(cdkey, uuid, self.dbsession)
        
            if dbmapb is None:
                ShopConfigService.log.e('bindUuidCDkey:error %s' % cdkey)                
                json.res = {'ret':103, 'msg':'cdkey invalid'}
        
            filname="%s/shop_config_%s_%s.sqlite" % (SrvConfig.getSQLiteFilePath(), dbmapb[0], dbmapb[1])
          
            file_object = open(filname, 'rb')
            sb = file_object.read()
            file_object.close()

            res.content_type = 'application/octet-stream'
            res.body = sb         
        except Exception, e: 
            ShopConfigService.log.e('ShopConfigService.getConfigAll: exception:%s' % e)
            res.json = {'ret':-1, 'msg':'exceptioin'}
        



        
        

    
    
        
